
require("dotenv").config()
const SmsClient = require("@alicloud/sms-sdk")
const accessKeyId = process.env.AccessKeyId //我的AccessKeyId
const accessKeySecret = process.env.AccessKeySecret //我的密钥
const signName = "易淘宝" //我的签名
const templateCode = "SMS_475530080" //我的模版

const client = new SmsClient({
    accessKeyId,
    secretAccessKey:accessKeySecret,
    endpoint:"https://dysmsapi.aliyuncs.com"
})

let phone_code = []
const send = (phone)=>{
    let code = Math.floor(1000 + Math.random()*9000).toString()
    let params = {
        PhoneNumbers:phone,
        SignName:signName,
        TemplateCode:templateCode,
        TemplateParam:JSON.stringify({"code":code})
    }
    return client.sendSMS(params).then(()=>{
        phone_code.push({phone,code,create:Date.now()})
        return code
    }).catch((err)=>{
        console.log(err,'7895643132')
        throw err
    })
}

const yz = (phone,code)=>{
    let index = phone_code.findIndex(i=>i.phone===phone)
    let time = Date.now()
    if(index!==-1){
        let use = phone_code[index]
        if(code === use.code){
            phone_code.splice(index,1)
            if(time-use.create < 1000*60*2){
                return {code:200,msg:"验证码正确"}
            }else{
                return {code:207,msg:'验证码已过期'}
            }
        }
    }
    return {code:201,msg:"验证码错误"}
}

module.exports = {send,yz}